package edu.johnpank.libassistant.services

import edu.johnpank.libassistant.entity.User
import edu.johnpank.libassistant.repo.UserRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.Optional

@Service
class UserService(
    @Autowired
    private val userRepository: UserRepository
) {

    fun getAllUser(): MutableList<User>{
        return userRepository.findAll() as MutableList<User>
    }

    fun getUserById(id: Long): User{
        return userRepository.findById(id).get()
    }

    fun getUserByLogin(login: String): Optional<User>{
        return userRepository.findByLogin(login)
    }

    fun findUserByString(string: String): MutableList<User>{
        return userRepository.findByLoginContainingOrFirstNameContaining(string, string) as MutableList<User>
    }

    @Transactional
    fun addUser(user: User){
        userRepository.save(user)
    }

    @Transactional
    fun updateUser(user: User){
        userRepository.save(user)
    }

    @Transactional
    fun deleteUser(user: User){
        userRepository.delete(user)
    }
}